@ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

REM 2009-2-4 16:20:36
REM 2009-8-27 10:07:25
REM Usage:
REM pfbak.cmd APP_NAME
REM   where APP_NAME is the dirname of the application
REM   located under C:\Program Files
REM Optionally, directly run pfbak.cmd, it will prompt
REM you to enter the APP_NAME. Here you may enter 'q'
REM to quit
if exist "%ProgramFiles%\WinRAR\winrar.exe" set RAR_EXE="%ProgramFiles%\WinRAR\winrar.exe"
if exist "%ProgramFiles(x86)%\WinRAR\winrar.exe" set RAR_EXE="%ProgramFiles(x86)%\WinRAR\winrar.exe"
if exist "%ProgramW6432%\WinRAR\winrar.exe" set RAR_EXE="%ProgramW6432%\WinRAR\winrar.exe"

set RAR_OPTIONS=-agYYYY.MM.DD_HH.MM.SS -m5 -rr3p -ms -tsm4 -tsc1 -tsa1 -ep1
set DEST_DIR=%cd%

REM application name
if not x"%~1"==x"" (
    set APP_NAME=%~nx1
)
if not defined APP_NAME (
    echo Please enter the application folder name stored
    echo under your "%PROGRAMFILES%"
    set /P APP_NAME=?
)
if "!APP_NAME!"=="q" echo Quit...&&goto error
echo OK, your desired application name is: %APP_NAME%

REM store current wording directory
pushd !CD!

if exist "%ProgramFiles%\%APP_NAME%" set my_prog_files=%ProgramFiles%
if exist "%ProgramFiles(x86)%\%APP_NAME%" set my_prog_files=%ProgramFiles(x86)%
if exist "%ProgramW6432%\%APP_NAME%" set my_prog_files=%ProgramW6432%

if exist "!my_prog_files!\%APP_NAME%" (
    cd /d "!my_prog_files!\%APP_NAME%"
    if errorlevel 1 echo ERROR: "!my_prog_files!\%APP_NAME%": cannot chdir&&goto error
    for /f "delims=*" %%i in ("!CD!") do set APP_DIR=%%~nxi
) else (
    echo ERROR: %APP_NAME%: not exists under any "Program Files" folder.&&goto error
)
echo OK, the application dir is "%APP_DIR%" under "!my_prog_files!"
echo     and we are now at: !CD!

REM =====================================================================

set app_install=!my_prog_files!\!APP_DIR!
if not exist !app_install! echo ERROR: !app_install!: not exists&&goto error

REM read specific backup options
if exist _backup_options.txt  (
    for /f "eol=; tokens=* delims=" %%i in (_backup_options.txt) do (
        set RAR_OPTIONS=!RAR_OPTIONS! %%i
    )
)

REM backup destination
if exist D:\!username!\download set backup_dest=D:\!username!\download&&goto begin_backup
if exist D:\!username! set backup_dest=D:\!username!&&goto begin_backup
if exist D:\ set backup_dest=D:\&&goto begin_backup
set backup_dest=\

:begin_backup
popd
REM summary
echo OK, BACKUP will:
echo   From: !app_install!
echo   To  : !backup_dest!
echo   Opts: !RAR_OPTIONS!
echo   PWD : !CD!

%RAR_EXE% a !RAR_OPTIONS! "!backup_dest!\!APP_DIR!-" "!app_install!"

goto end

:error
pause

:end
ENDLOCAL
@ECHO ON
